package org.lmind.example.common.web.spring;

import javax.servlet.ServletContext;

import org.lmind.example.common.web.ApplicationContext;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.context.ServletContextAware;

public class WebAppInitializer implements ServletContextAware, InitializingBean {
	
	private static Object LOCK = new Object(); 
	
	private volatile static WebAppInitializer instance;
	
	private ServletContext servletContext;
	
	private ApplicationContext applicationContext;
	
	public static WebAppInitializer currentInstance() {
		return instance;
	}

	public WebAppInitializer() {
		synchronized (LOCK) {
			if (instance != null)
				throw new IllegalStateException("WebAppInitializer只能有一个实例");
			instance = this;
		}
	}

	public void setWebAppContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		servletContext.setAttribute(ApplicationContext.WEB_APP_CONTEXT_NAME, applicationContext);
	}

}
